# -*- coding: utf-8 -*-
import re
import json
import requests
from requests import exceptions
from bs4 import BeautifulSoup
from .result import result

CHECK_SSFW_URL = 'http://ssfw.hlju.edu.cn/ssfw/j_spring_ids_security_check'
COURSES_URL = 'http://ssfw.hlju.edu.cn/ssfw/xkgl/xkjgcx.do'

week_dict={'星期一':1,'星期二':2,'星期三':3,'星期四':4,'星期五':5,'星期六':6,'星期日':7}

def request_courses(uid,token):
    cookie = {'iPlanetDirectoryPro':token}

    data = None
    for i in range(10):
        print('request courses: ',i)
        if data != None:
            break
        try:
            session = requests.session()
            session.get(CHECK_SSFW_URL,cookies = cookie,timeout=2)
            req = session.get(COURSES_URL,cookies = cookie,timeout=2)

            # 暂定，还不是十分确定在验证过期时，是否返回的内容长度小于 14000
            # if int(req.headers['Content-Length']) < 14000:
            #     continue
            html = req.content
        except requests.Timeout as e:
            print('request courses timeout')
            continue

        except requests.ConnectionError as e:
            print('request courses connection')
            return result(107)

        except Exception as e:
            print('request courses exception',e)
            return result(105)

        data = parse_courses(uid,html)

    # if there still have no data after 10 times tried, it means verify expired
    if data == None:
        return result(108)

    return result(100,data)


# parse courses from html data
def parse_courses(uid,html):

    table = BeautifulSoup(html,'html.parser').find('table')
    if table == None:
        return None

    trs = table.find_all('tr')

    json_list = []

    for tr in trs:
        item_list = tr.find_all('td')
        if len(item_list) < 10:
            continue

        time_list = item_list[5].get_text(' ').split(' ')
        loc_list = item_list[6].get_text(' ').split(' ')

        if len(time_list)%3 == 0 :
            for i in range(0,int(len(time_list)/3)) :
                terms = item_list[0].get_text(strip = True).split(' ')
                schoolYear = '--' if len(terms) < 2 else terms[0]
                term = '--' if len(terms) < 2 else terms[1]
                cid = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
                cn = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
                period = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)
                credit =  0.0 if len(item_list[4].get_text(strip = True)) == 0 else float(item_list[4].get_text(strip = True))

                pattern = re.compile(r'\d{1,2}')#提取时间字符串中的数字
                week = pattern.findall(time_list[0+i*3])
                section = pattern.findall(time_list[2+i*3])

                bs = 0 if len(section) == 0 else int(section[0])
                es = 0 if len(section) == 0 else int(section[1])
                bw = 0 if len(week) == 0 else int(week[0])
                ew = 0 if len(week) == 0 else int(week[1])

                # dayStr=time_list[1+i*3]
                # print('day is:',dayStr)
                day = week_dict.get(time_list[1+i*3])

                cr = loc_list[1+i*2]
                teacher = u'--' if len(item_list[7].get_text(strip = True)) == 0 else item_list[7].get_text('|').split('|')[0]
                campus = u'--'  if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)
                sty = u'正常' if len(item_list[9].text) == 0 else item_list[9].text
                sm = u'初修' if len(item_list[10].text) == 0 else item_list[10].text

                if sty != u'免听':
                    json_list.append({'uid':uid,'schoolYear':schoolYear,'term':term,'cid':cid,'cname':cn,'period':period,'credit':credit,
                    'startSection':bs,'endSection':es,'startWeek':bw,'endWeek':ew,'dayOfWeek':day,'classroom':cr,'teacher':teacher,
                    'campus':campus,'studyType':sty,'studyMethod':sm})

    return json_list

if __name__ == '__main__':
    data = request_courses('20135081','AQIC5wM2LY4Sfcw1LQpOUCsV8Zuz0KwAWjIwouJN7Hn1YSA%3D%40AAJTSQACMDI%3D%23').encode('utf-8')
    print(data)
